package org.cocos2dx.javascript.Advert.gdt;

import android.app.Activity;
import android.graphics.Point;
import android.util.Log;
import android.view.Gravity;
import android.widget.FrameLayout;

import com.qq.e.ads.banner2.UnifiedBannerADListener;
import com.qq.e.ads.banner2.UnifiedBannerView;
import com.qq.e.comm.util.AdError;

import org.cocos2dx.javascript.Advert.core.AdBase;

public class GDTBannerAd extends AdBase implements UnifiedBannerADListener {

    UnifiedBannerView mUnifiedBannerView;
    FrameLayout mContainer;

    @Override
    public void onNoAD(AdError adError) {
        Log.d("gdt GDTBannerAd", adError.getErrorCode() + "onNoAD: " + adError.getErrorMsg());
    }

    @Override
    public void onADReceive() {
        Log.d("gdt GDTBannerAd", "onADReceive: ");
        mLoaded = true;
        if (mShow) {
            showAd(mActivity);
        }
    }

    @Override
    public void onADExposure() {

    }

    @Override
    public void onADClosed() {
        Log.d("gdt GDTBannerAd", "onADClosed: ");
    }

    @Override
    public void onADClicked() {

    }

    @Override
    public void onADLeftApplication() {

    }

    @Override
    public void loadAd(Activity activity, boolean show) {
        mActivity = activity;
        mShow = show;
        if (mUnifiedBannerView == null) {
            mUnifiedBannerView = new UnifiedBannerView(mActivity, GDTConstants.BannerPosID, this);
        }
        mUnifiedBannerView.loadAD();
    }

    @Override
    public void showAd(Activity activity) {
        if (!mLoaded) {
            loadAd(activity, true);
            return;
        }
        mLoaded = false;
        if (mContainer == null) {
            mContainer = (FrameLayout) mActivity.findViewById(android.R.id.content).getRootView();
            mContainer.addView(mUnifiedBannerView, getUnifiedBannerLayoutParams());
        }
    }

    public void closeAd() {
        if (mUnifiedBannerView != null) {
            if (mContainer != null) {
                mContainer.removeView(mUnifiedBannerView);
            }
            mUnifiedBannerView.destroy();
        }
        mUnifiedBannerView = null;
        mContainer = null;
    }

    private FrameLayout.LayoutParams getUnifiedBannerLayoutParams() {
        float scale = 6.4F;
        Point screenSize = new Point();
        mActivity.getWindowManager().getDefaultDisplay().getSize(screenSize);
        return new FrameLayout.LayoutParams(screenSize.x, Math.round(screenSize.x / scale), Gravity.TOP);
    }
}
